/*
 * @Author: dongdong.wu
 * @Date: 2020-11-04 10:55:57
 * @LastEditTime: 2020-11-09 11:34:01
 * @FilePath: \ncim_web\src\components\weComponents\weColumnTable\validator.js
 * @Description: 策略模式生成表单验证  TODO 待优化是否提出Rule作为校验对象
 */
// 策略池
const strategies = {
  required: function(value, msg, prop) {
    if (typeof value === 'undefined' || value === null || value === '') {
      return {
        valid: false,
        prop: prop,
        value,
        msg
      }
    } else {
      return {
        valid: true,
        value
      }
    }
  }
}

/**
 * validator
 */

//  校验数据池
const Validator = function() {
  this.rules = []
}
// 策略选择保存校验模式
Validator.prototype.add = function(data, prop, rule, errorMsg) {
  this.rules.push(function() {
    return strategies[rule].call(null, data[prop], errorMsg, prop)
  })
}
// 校验并返回信息
/**
 * 返回valid以及msg的集合
 */
Validator.prototype.validate = async function() {
  const validateFuncList = []
  for (var i = 0, validatorFunc; (validatorFunc = this.rules[i++]); ) {
    const { valid } = validatorFunc()
    if (!valid) {
      validateFuncList.push(validatorFunc())
    }
  }
  return validateFuncList
}

export default Validator
